package com.example.aspect;

import com.example.enums.DataSourceType;
import com.example.utils.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * com.example.aspect.ReadWriteSplitAspect
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/10/30 22:13
 */
@Aspect
@Component
public class ReadWriteSplitAspect {

    // 切入点：拦截所有 mapper 接口方法
    @Pointcut("execution(* com.example.mapper.*.*(..))")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();

        // 自动识别读写操作
        // 读操作方法：get、select、query、find、list
        // 写操作方法：insert、update、delete、save
        DataSourceType dataSourceType;
        if (methodName.startsWith("get") || methodName.startsWith("select") ||
                methodName.startsWith("query") || methodName.startsWith("find") ||
                methodName.startsWith("list")) {
            dataSourceType = DataSourceType.SLAVE;
        } else {
            dataSourceType = DataSourceType.MASTER;
        }

        // 设置数据源类型
        DataSourceContextHolder.setDataSourceType(dataSourceType);

        try {
            // 执行方法
            return point.proceed();
        } finally {
            // 清除数据源类型
            DataSourceContextHolder.clearDataSourceType();
        }
    }
}
